import React, { Component, Fragment } from 'react'
import { Form, Input, Button, Checkbox,message } from 'antd';
import LoginCss from "./Login.module.css";
import 'antd/dist/antd.css';
import { RequestLogin } from "../../api/IndexApi";
import Sha256 from "js-sha256";
import {SaveUserLocal  } from "../../common/UserStore.js";
import { store } from "../../store";
import { menuList } from "../../store/action";

// 记住密码复选框位置
const tailLayout = {
    wrapperCol: {
        offset: 8,
        span: 16,
    },
};

// 函数组件
const index = (props) => {
    const onFinish = values => {
        const password = Sha256(values.password); //加密码
        RequestLogin(values.username,password).then(data => {
            if (data.resultCode === 1) {
                store.dispatch(menuList()); //redux
                // 保存登录状态
                SaveUserLocal(values);
                props.history.push({ pathname: '/main' })
            }else{
                message.info('用户名或密码出错！');
            }
        }).catch(err=>{
            message.info('网络出错!'+err);
        })
    };

    const onFinishFailed = errorInfo => {
        console.log('Failed:', errorInfo);
    };

    return (
        <div className={LoginCss.wrap}>
            <Form
                className={LoginCss.loginForm}
                name="basic"
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >
                <h2>后台中心</h2>
                <Form.Item
                    style={{ width: '80%' }}
                    label="用户名"
                    name="username"
                    rules={[
                        {
                            required: true,
                            message: '请输入用户名!',
                        },
                    ]}
                >
                    <Input className={LoginCss.itemInput} />
                </Form.Item>

                <Form.Item
                    style={{ width: '80%' }}
                    label="密&nbsp;&nbsp;&nbsp;码"
                    name="password"
                    rules={[
                        {
                            required: true,
                            message: '请输入密码!',
                        },
                    ]}
                >
                    <Input.Password className={LoginCss.itemInput} />
                </Form.Item>

                <Form.Item {...tailLayout} name="remember" valuePropName="checked" className={LoginCss.itemInput}>
                    <Checkbox>记住密码</Checkbox>
                </Form.Item>

                <Form.Item >
                    <Button type="primary" htmlType="submit" style={{ width: 100 }}>
                        登录
          </Button>
                </Form.Item>
            </Form>
        </div>
    );
};

export default index;